<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use iflow\facade\Session;
use iflow\Response;
use think\model\relation\HasOne;

class userOauthKeyModel extends QueryModel
{
    protected $table = "user_oauth_key";

    public function hasUser(): HasOne {
        return $this->hasOne(userModel::class, 'uid', 'uid');
    }

    // 第三方授权登录
    public function login(array $userInfo, string $type = "wechat_openid", bool $autoRegister = false): Response {
        $user = $this->withJoin([
            'hasUser' => [
                'user_name' => 'user_name',
                'user_group_id' => 'user_group_id',
                'avatar' => 'avatar',
                'signature' => 'signature',
                'role' => 'role'
            ]
        ], 'LEFT') -> where([
            'oauth_openid' => $userInfo['openid'],
            'type' => $type
        ]) -> findOrEmpty();

        if ($user -> isEmpty() && !$autoRegister) {
            return message() -> update_failed('授权成功， 请绑定手机/邮箱后进行下一步操作', $userInfo);
        }

        if ($user -> isEmpty() && $autoRegister) {
            $user = (new userModel()) -> createData([
                'user_name' => md5($userInfo['nickname'] . $userInfo['openid'] . rand(9999, 999999)),
                'nick_name' => $userInfo['nickname'],
                'avatar' => $userInfo['headimgurl'],
                'signature' => '系统原装签名，送给每一个小可爱',
                'user_group_id' => 2,
                'email' => $userInfo['openid'].'@domain.com',
                'phone' => microtime() . rand(9999, 99999),
            ]);

            if ($user -> data['items']) {
                $user = $user -> data['items'];
                $user['uid'] = $user['id'];
                $this->bindOpenId($user['id'], $userInfo['openid'], $type);
            } else {
                return $user;
            }
        }

        // 用户登录所在域名
        $user['domain'] = request() -> getHeader('host');
        $user['authorization'] = Session::getSessionId();

        session('userInfo', $user);
        return message() -> success('登录成功', $user);
    }

    public function bindOpenId(int $uid, string $openid, string $type): Response {
        $info = $this->where([
            'oauth_openid' => $openid,
            'type' => $type
        ]) -> findOrEmpty();

        if ($info -> isExists())
            return message() -> update_failed('该账户已绑定该平台， 无法重复绑定');

        $data = self::create([
            'uid' => $uid,
            'oauth_openid' => $openid,
            'type' => $type
        ]) -> toArray();
        return message() -> success('绑定成功', $data);
    }
}